#include "stdafx.hpp"
#include "ColligereXmlDataExporter.hpp"

void col::XmlDataExporter::Export ( col::DatabaseInterfaceBase &rFrom,
								   const wxString &rToFile )
{
	mpFrom = &rFrom;
	DataExporterEvent evt_export_start ( COLLIGERE_EVT_EXPORT_START, this );
	rFrom.GetLayout()->ProcessEvent ( evt_export_start );

	wxXmlDocument doc;
	doc.SetRoot ( new wxXmlNode ( wxXML_ELEMENT_NODE, "collection" ) );

	wxXmlNode *previous = 0;
	foreach ( const DatabaseItemBasePtr item, rFrom.GetHandler()->GetItems() )
	{
		wxXmlNode *n = new wxXmlNode ( *ExportItem ( item.get() ) );
		if ( !previous )
		{
			doc.GetRoot()->AddChild(n);
		}
		else
		{
			doc.GetRoot()->InsertChildAfter ( n, previous );
		}
		previous = n;

		DataExporterEvent evt_item_exported ( COLLIGERE_EVT_ITEM_EXPORTED, this, item.get() );
		rFrom.GetLayout()->ProcessEvent ( evt_item_exported );
	}
	doc.Save ( rToFile );

	DataExporterEvent evt_export_end ( COLLIGERE_EVT_EXPORT_END, this );
	rFrom.GetLayout()->ProcessEvent ( evt_export_end );
}

wxXmlNode *col::XmlDataExporter::ExportItem ( const DatabaseItemBase *pItem )
{
	wxXmlNode *node = new wxXmlNode ( wxXML_ELEMENT_NODE,
		pItem->GetTableDescriptor().GetItemName() );

	for ( wxUint32 col = 0; col < pItem->GetColumnCount(); ++col )
	{
		wxXmlNode *elem = new wxXmlNode ( wxXML_ELEMENT_NODE,
			pItem->GetTableDescriptor().GetColumnNameByIndex ( col ) );

		elem->AddChild ( new wxXmlNode ( wxXML_TEXT_NODE,
			pItem->GetTableDescriptor().GetColumnNameByIndex ( col ),
			pItem->GetColumnValue ( col ) ) );

		wxXmlNode *previous = 0;

		if ( !previous )
		{
			node->AddChild ( elem );
			previous = elem;
		}
		else
		{
			node->InsertChildAfter ( elem, previous );
			previous = elem;
		}
	}
	if ( pItem->GetChildCount() != 0 )
	{
		wxXmlNode *children = new wxXmlNode ( wxXML_ELEMENT_NODE,
			pItem->GetLastChild()->GetTableDescriptor().GetName() );

		wxXmlNode *previous = 0;
		foreach ( const DatabaseItemBasePtr &child, pItem->GetChildren() )
		{
			wxXmlNode *child_node = ExportItem ( &(*child) );
			if ( previous )
			{
				children->InsertChildAfter ( child_node, previous );
				previous = child_node;
			}
			else
			{
				children->AddChild ( child_node );
				previous = child_node;
			}
		}
		node->AddChild ( children );
	}
	return node;
}

wxUint32 col::XmlDataExporter::GetItemCount() const
{
	wxASSERT ( mpFrom );
	return mpFrom->GetHandler()->GetItemCount();
}